<script setup>
import { appStore } from '@/sotre/modules/app';
import { onShow } from '@dcloudio/uni-app';

const { userInfo } = toRefs(appStore());
const $post = inject('$post');
const $get = inject('$get');

const currentIntegral = ref(0); // 当前积分
const selectedIntegral = ref(0); // 选中的积分
const customAmount = ref(''); // 自定义金额
const isCustom = ref(false); // 是否自定义充值

// 预设积分选项（积分值）
const presetOptions = [1000, 2000, 5000, 10000, 16000, 20000];
const ratio = 20; // 充值比例 1:20

// 获取当前积分
const getCurrentIntegral = async () => {
    try {
        const { data } = await $get(`/platform/integral/get/${userInfo.value.lastEnterpriseId}`);
        currentIntegral.value = data || 0;
    } catch (error) {
        console.error('获取积分失败:', error);
    }
};

// 计算选中金额
const selectedAmount = computed(() => {
    if (isCustom.value && customAmount.value) {
        return parseFloat(customAmount.value).toFixed(2) || '0.00';
    }
    return (selectedIntegral.value / ratio).toFixed(2);
});

// 计算最终获得的积分
const finalIntegral = computed(() => {
    if (isCustom.value && customAmount.value) {
        const amount = parseFloat(customAmount.value) || 0;
        return Math.floor(amount * ratio);
    }
    return selectedIntegral.value;
});

// 选择预设选项
const selectPreset = integral => {
    selectedIntegral.value = integral;
    isCustom.value = false;
    customAmount.value = '';
};

// 切换到自定义输入
const toggleCustom = () => {
    isCustom.value = true;
    selectedIntegral.value = 0;
    customAmount.value = '';
};

// 立即充值
const handleRecharge = () => {
    const amount = parseFloat(selectedAmount.value);
    const integral = finalIntegral.value;

    if (amount <= 0 || isNaN(amount)) {
        uni.showToast({
            title: '请选择或输入充值金额',
            icon: 'none',
        });
        return;
    }

    if (!integral || integral <= 1) {
        uni.showToast({
            title: '充值金额必须大于1',
            icon: 'none',
        });
        return;
    }

    // 检查是否为主账号
    if (!userInfo.value.currEnterpriseByCache?.main) {
        return uni.showToast({
            title: '您不是当前企业主账号，暂无权限充值',
            icon: 'none',
            duration: 2000,
        });
    }

    uni.showLoading({
        title: '支付中...',
    });

    // #ifdef MP-WEIXIN || APP-PLUS
    $post(`/platform/integral/order/jsapi?money=${amount}&openId=${userInfo.value.wxOpenid}`)
        .then(res => {
            if (res.code === 200) {
                uni.requestPayment({
                    ...res.data.pay,
                    success: () => {
                        uni.hideLoading();
                        uni.showToast({
                            title: '充值成功',
                            icon: 'success',
                        });
                        getCurrentIntegral();
                        // 重置选择
                        selectedIntegral.value = 0;
                        isCustom.value = false;
                        customAmount.value = '';
                    },
                    fail: () => {
                        uni.hideLoading();
                        uni.showToast({
                            title: '支付失败',
                            icon: 'none',
                        });
                    },
                });
            } else {
                uni.hideLoading();
            }
        })
        .catch(() => {
            uni.hideLoading();
        });
    // #endif

    // #ifdef H5
    uni.hideLoading();
    uni.showToast({
        title: '暂不支持当前环境支付，请前往微信小程序支付',
        icon: 'none',
        duration: 2000,
    });
    // #endif
};

onShow(() => {
    if (userInfo.value?.lastEnterpriseId) {
        getCurrentIntegral();
    }
});
</script>

<template>
    <div class="integral">
        <u-navbar title="钻石充值" placeholder autoBack></u-navbar>

        <!-- 当前积分显示 -->
        <div class="current-integral">
            <div class="label">当前钻石</div>
            <div class="value">{{ currentIntegral }}</div>
        </div>

        <!-- 充值比例说明 -->
        <div class="ratio-tip">
            <text>充值比例：1元 = {{ ratio }}钻石</text>
        </div>

        <!-- 预设选项 -->
        <div class="preset-section">
            <div class="section-title">选择充值金额</div>
            <div class="preset-grid">
                <div
                    v-for="(integral, index) in presetOptions"
                    :key="index"
                    class="preset-item"
                    :class="{ active: !isCustom && selectedIntegral === integral }"
                    @click="selectPreset(integral)"
                >
                    <div class="integral-value">{{ integral }}</div>
                    <div class="amount">¥{{ (integral / ratio).toFixed(0) }}</div>
                </div>
            </div>
        </div>

        <!-- 自定义充值 -->
        <div class="custom-section">
            <div class="section-title">自定义充值</div>
            <div class="custom-input-wrapper">
                <u-input
                    v-model="customAmount"
                    type="number"
                    placeholder="请输入充值金额（元）"
                    clearable
                    @focus="toggleCustom"
                ></u-input>
                <div class="input-tip">可获得 {{ finalIntegral }} 钻石</div>
            </div>
        </div>

        <!-- 底部充值按钮 -->
        <div class="bottom-bar">
            <div class="total-info">
                <div class="total-label">需支付</div>
                <div class="total-amount">¥{{ selectedAmount }}</div>
            </div>
            <u-button type="warning" shape="circle" @click="handleRecharge">立即充值</u-button>
        </div>
    </div>
</template>

<style scoped lang="scss">
.integral {
    min-height: 100vh;
    background: #f5f5f5;

    // 当前积分显示
    .current-integral {
        background: linear-gradient(135deg, #e9defa 0%, #fbfcdb 100%);
        margin: 30rpx 24rpx;
        padding: 40rpx 28rpx;
        border-radius: 24rpx;
        text-align: center;
        color: #2b2b2b;

        .label {
            font-size: 26rpx;
            opacity: 0.8;
            margin-bottom: 12rpx;
        }

        .value {
            font-size: 64rpx;
            font-weight: 700;
            letter-spacing: 2rpx;
        }
    }

    // 充值比例提示
    .ratio-tip {
        text-align: center;
        padding: 16rpx 24rpx;
        color: #999;
        font-size: 24rpx;
    }

    // 预设选项区域
    .preset-section {
        margin: 24rpx 24rpx 0 24rpx;
        background: #fff;
        border-radius: 24rpx;
        padding: 24rpx;

        .section-title {
            font-size: 30rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 20rpx;
        }

        .preset-grid {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            gap: 16rpx 12rpx;

            .preset-item {
                width: 27.5%;
                background: #f5f5f6;
                border: 2rpx solid transparent;
                border-radius: 16rpx;
                padding: 28rpx 10rpx;
                text-align: center;
                transition: all 0.2s;

                .integral-value {
                    font-size: 30rpx;
                    font-weight: 700;
                    color: #333;
                    margin-bottom: 8rpx;
                }

                .amount {
                    font-size: 24rpx;
                    color: #f9712e;
                    font-weight: 600;
                }

                &.active {
                    background: #fff5f0;
                    border-color: #f9712e;

                    .integral-value {
                        color: #f9712e;
                    }
                }
            }
        }
    }

    // 自定义充值区域
    .custom-section {
        margin: 24rpx;
        background: #fff;
        border-radius: 24rpx;
        padding: 24rpx;

        .section-title {
            font-size: 30rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 20rpx;
        }

        .custom-input-wrapper {
            :deep(.u-input) {
                --u-input-height: 88rpx;
                --u-input-font-size: 28rpx;
                --u-input-padding: 0 24rpx;
                background: #f8f9fa;
                border: 2rpx solid #e5e5e5;
                border-radius: 16rpx;
            }

            .input-tip {
                margin-top: 12rpx;
                text-align: right;
                font-size: 26rpx;
                color: #f9712e;
                font-weight: 600;
            }
        }
    }

    // 底部充值栏
    .bottom-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #fff;
        padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom)) 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 -8rpx 20rpx rgba(0, 0, 0, 0.06);
        z-index: 100;

        .total-info {
            display: flex;
            flex-direction: column;
            align-items: flex-start;

            .total-label {
                font-size: 22rpx;
                color: #999;
                margin-bottom: 6rpx;
            }

            .total-amount {
                font-size: 40rpx;
                font-weight: 700;
                color: #f9712e;
            }
        }

        :deep(.u-button) {
            padding: 0 44rpx;
            height: 80rpx;
            line-height: 80rpx;
            font-size: 28rpx;
            width: fit-content;
            margin: 0;
        }
    }
}
</style>
